package cn.yunhe.dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import cn.yunhe.dao.BoardDao;
import cn.yunhe.entity.Board;
import cn.yunhe.entity.User;
import cn.yunhe.util.C3P0Util;
/**
 * 版块信息 数据库操作
 * 
 * @author qph
 *
 */
public class BoardDaoImpl implements BoardDao {

	@Override
	public boolean addBoard(Board board) {
		int num = -1;
		Connection conn = C3P0Util.getConnection();
		StringBuilder sql = new StringBuilder();
		sql.append(" insert into tb_board(bname) ");
		sql.append(" values(?)");
		PreparedStatement ps = null;
		try {
			conn.setAutoCommit(false);
			ps = conn.prepareStatement(sql.toString());
			ps.setString(1, board.getName());
			num = ps.executeUpdate();
			conn.commit();
			if (num > 0) {
               return true;
			}else{
				return false;
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return false;
		}finally {
			C3P0Util.close(null, ps, conn);
		}

	}

	@Override
	public boolean updateBoard(Board board) {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public List<Board> findAllBoard() {
		List<Board> list = new ArrayList<Board>();
		Connection conn = C3P0Util.getConnection();
		StringBuilder sql = new StringBuilder();
		sql.append(" select bid,bname  ");
		sql.append(" from tb_board");
		sql.append(" order by bid");
		PreparedStatement ps = null;
		ResultSet rs = null;
		try {
			ps = conn.prepareStatement(sql.toString());
			rs = ps.executeQuery();
			while(rs.next()) {
				Board board = new Board();
				board.setId(rs.getInt("bid"));
				board.setName(rs.getString("bname"));
				list.add(board);
			}
			return list;
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return list;
		} finally {
			C3P0Util.close(rs, ps, conn);
		}

	}

	@Override
	public Board getBoardById(int bid) {
		Board board = null;
		Connection conn = C3P0Util.getConnection();
		StringBuilder sql = new StringBuilder();
		sql.append(" select bid,bname  ");
		sql.append(" from tb_board");
		sql.append(" where  bid= ?");
		PreparedStatement ps = null;
		ResultSet rs = null;
		try {
			ps = conn.prepareStatement(sql.toString());
			ps.setInt(1, bid);
			rs = ps.executeQuery();
			if(rs.next()) {
				board = new Board();
				board.setId(rs.getInt("bid"));
				board.setName(rs.getString("bname"));	
			}
			return board;
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return board;
		} finally {
			C3P0Util.close(rs, ps, conn);
		}

	}

}
